# -*- coding: utf-8 -*-
import sys

sys.path.append('../')
from common.config import *
from db.mysql import MysqlClient
from itertools import product
import requests, json
from common.helper import Helper


class Spider(object):

    def __init__(self):

        self.mysql = MysqlClient()
        self.name = "e无忧泰康重疾保"

    # 生成产品数据
    def genProductInfo(self):

        plan = {
            "planA": {
                # 年龄段
                "year": [str(i) for i in range(18, 51)],
                # 性别
                "gender": ["M", "F"],
                # 重大疾病保险金
                "serious_money": ["100000"],
                # 轻症保险金
                "slight_money": ["20000"],
                # 保障期限
                "expire": ["1年"],
                # 缴费方式
                "payType": ["年缴"],
                # 投保对象
                "payObject": ["本人/父母/配偶"]
            },
            "planB": {
                # 年龄段
                "year": [str(i) for i in range(18, 51)],
                # 性别
                "gender": ["M", "F"],
                # 重大疾病保险金
                "serious_money": ["200000"],
                # 轻症保险金
                "slight_money": ["40000"],
                # 保障期限
                "expire": ["1年"],
                # 缴费方式
                "payType": ["年缴"],
                # 投保对象
                "payObject": ["本人/父母/配偶"]
            },
            "planC": {
                # 年龄段
                "year": [str(i) for i in range(0, 18)],
                # 性别
                "gender": ["M", "F"],
                # 重大疾病保险金
                "serious_money": ["100000"],
                # 轻症保险金
                "slight_money": ["20000"],
                # 保障期限
                "expire": ["1年"],
                # 缴费方式
                "payType": ["年缴"],
                # 投保对象
                "payObject": ["子女"]
            },
            "planD": {
                # 年龄段
                "year": [str(i) for i in range(0, 18)],
                # 性别
                "gender": ["M", "F"],
                # 重大疾病保险金
                "serious_money": ["200000"],
                # 轻症保险金
                "slight_money": ["40000"],
                # 保障期限
                "expire": ["1年"],
                # 缴费方式
                "payType": ["年缴"],
                # 投保对象
                "payObject": ["子女"]
            },
        }
        for k in plan:
            for v in product(plan[k]["year"], plan[k]["gender"], plan[k]["serious_money"], plan[k]["slight_money"],
                             plan[k]["expire"], plan[k]["payType"], plan[k]["payObject"]):
                self.mysql.cursor.execute(domain[self.name]["insert_sql"].format(
                    v[0], v[1], v[2], v[3], v[4], v[5], v[6]
                ))
                self.mysql._conn.commit()
                print(
                    domain[self.name]["insert_sql"].format(
                        v[0], v[1], v[2], v[3], v[4], v[5], v[6]
                    )
                )

    # 执行爬虫
    def requestJson(self, dt=None):

        if dt["serious_money"] == "200000":
            data = {
                "calculateData": {"calstartDate": "2020-02-15 00:00:00", "insuredType": "famliy",
                                  "planId": "1007A02G01",
                                  "liabilityContents": [
                                      {"liabilityId": "1007013", "amount": "200000", "liabilityName": "重大疾病保险金",
                                       "liabilityAmount": "20万"},
                                      {"liabilityId": "1007002", "amount": "40000", "liabilityName": "轻症疾病保险金",
                                       "liabilityAmount": "4万"}]}, "insuredData": [
                    {"index": 1, "insuredRelationship": "40", "insuredAge": dt["year"], "insuredGender": "1" if dt["gender"] == "M" else "2",
                     "insuredBirth": "{year}-01-01".format(year = str(2020-int(dt["year"]))), "minimum": "18", "maximum": "50", "planLiabilityList": [
                        {"liabilityId": "1007013", "amount": "200000", "liabilityName": "重大疾病保险金",
                         "liabilityAmount": "20万"},
                        {"liabilityId": "1007002", "amount": "40000", "liabilityName": "轻症疾病保险金",
                         "liabilityAmount": "4万"}],
                     "liabilityContents": [{"liabilityId": "1007013", "amount": "200000", "liabilityName": "重大疾病保险金",
                                            "liabilityAmount": "20万"},
                                           {"liabilityId": "1007002", "amount": "40000", "liabilityName": "轻症疾病保险金",
                                            "liabilityAmount": "4万"}]}],
                "exchangeData": {"memberId": "", "memberToken": "", "applicationId": "1228155512386633728",
                                 "applicationToken": "b792bd735f1b628af6362421a696ea3a",
                                 "workqueueId": "1101751207178125312", "channelId": "3", "platformId": "pc",
                                 "referId": ""},
                "userDefine": {"from": "details"}}
        else:
            data = {"calculateData": {"calstartDate": "2020-02-15 00:00:00", "insuredType": "famliy",
                                      "planId": "1007A02G01", "liabilityContents": [
                    {"liabilityId": "1007013", "amount": "100000", "liabilityName": "重大疾病保险金",
                     "liabilityAmount": "10万"},
                    {"liabilityId": "1007002", "amount": "20000", "liabilityName": "轻症疾病保险金",
                     "liabilityAmount": "2万"}]}, "insuredData": [
                {"index": 1, "insuredRelationship": "50", "insuredAge": dt["year"], "insuredGender":  "1" if dt["gender"] == "M" else "2",
                 "insuredBirth": "{year}-01-01".format(year = str(2020-int(dt["year"]))), "minimum": "18", "maximum": "50", "planLiabilityList": [
                    {"liabilityId": "1007013", "amount": "100000", "liabilityName": "重大疾病保险金",
                     "liabilityAmount": "10万"},
                    {"liabilityId": "1007002", "amount": "20000", "liabilityName": "轻症疾病保险金", "liabilityAmount": "2万"}],
                 "liabilityContents": [{"liabilityId": "1007013", "amount": "100000", "liabilityName": "重大疾病保险金",
                                        "liabilityAmount": "10万"},
                                       {"liabilityId": "1007002", "amount": "20000", "liabilityName": "轻症疾病保险金",
                                        "liabilityAmount": "2万"}]}],
                    "exchangeData": {"memberId": "", "memberToken": "", "applicationId": "1228155512386633728",
                                     "applicationToken": "b792bd735f1b628af6362421a696ea3a",
                                     "workqueueId": "1101751207178125312", "channelId": "3", "platformId": "pc",
                                     "referId": ""}, "userDefine": {"from": "details"}}
        payload = json.dumps(data)

        r = requests.post(url=domain[self.name]["url"], headers=domain[self.name]["header"], data=payload)
        if r.status_code == 200 and "保费试算成功" in r.text:
            price = Helper.decimalParse(r.json()["data"]["sumPremium"])

            data = {
                "name":self.name,
                "id":dt["id"],
                "price":price
            }
            self.mysql.updatePrice( data )
        else:
            data = {
                "name":self.name,
                "id":dt["id"],
                "state":3
            }
            self.mysql.updateTask( data )
            print("\n/*产品价格数据更新失败:%d*/"%dt["id"])

    def main(self):

        while True:

            # 随机领取一条数据
            dt = self.mysql.randTask(self.name)

            if not dt:
                print("产品价格抓取完成~~~")

                return

            # 任务执行状态
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 1
            }
            self.mysql.updateTask(data)

            self.requestJson(dt)

